<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.spuName"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入商品名称"
      />
      <el-input
        v-model="listQuery.id"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入秒杀ID"
      />
      <el-select v-model="listQuery.status" clearable style="width: 200px" class="filter-item" placeholder="请选择秒杀状态" >
        <el-option v-for="(item,index) in statusMap" :key="index" :label="item.name" :value="item.value" />
      </el-select>
      <el-button v-permission="['operation:seckill:query']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['operation:seckill:create']" class="filter-item" type="primary" icon="el-icon-edit" @click="openSpuCreateDialog">添加</el-button>
    </div>
    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" class="table-expand">
            <el-form-item label="商品单位">
              <span>{{ props.row.unit }}</span>
            </el-form-item>
            <el-form-item label="类目ID">
              <span>{{ props.row.categoryId }}</span>
            </el-form-item>
            <el-form-item label="商品sku属性">
              <el-table :data="props.row.seckillSkuDTOList">
                <el-table-column align="center" prop="skuId" label="skuId"/>
                <el-table-column align="center" prop="title" label="skuTitle"/>
                <el-table-column align="center" prop="skuSeckillPrice" label="秒杀价格(元)"/>
                <el-table-column align="center" prop="stockCount" label="秒杀库存"/>
                <el-table-column align="center" prop="originalPrice" label="原始价格(元)"/>
                <el-table-column align="center" prop="price" label="售卖价格(元)"/>
                <el-table-column align="center" prop="vipPrice" label="会员价格(元)"/>
                <el-table-column align="center" prop="freeStockCount" label="冻结库存"/>
                <el-table-column align="center" prop="barCode" label="国际条码"/>
              </el-table>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column align="center" label="秒杀ID" prop="id" min-width="50%"/>

      <el-table-column align="center" label="商品(SPU)ID" prop="spuId" />

      <el-table-column align="center" min-width="100" label="名称" prop="title" />

      <el-table-column align="center" property="img" min-width="50" label="图片">
        <template slot-scope="scope">
          <img :src="scope.row.img" width="40" >
        </template>
      </el-table-column>
      <el-table-column align="center" label="活动状态" min-width="50" prop="status">
        <template slot-scope="scope">
          <el-tag
            :type="state_arr[scope.row.status] && state_arr[scope.row.status].type"
          >{{ state_arr[scope.row.status] && state_arr[scope.row.status].text }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="秒杀开始时间" prop="gmtStart" min-width="50">
        <template slot-scope="scope">{{ scope.row.gmtStart | formatGmt }}</template>
      </el-table-column>

      <el-table-column align="center" label="秒杀结束时间" prop="gmtEnd" min-width="50">
        <template slot-scope="scope">{{ scope.row.gmtEnd | formatGmt }}</template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="80%" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['operation:seckill:edit']" v-show="scope.row.status !== 1 && scope.row.status !== 4" type="primary" size="mini" @click="openSpuUpdateDialog(scope.row)">编辑</el-button>
          <el-button v-permission="['operation:seckill:delete']" v-show="scope.row.status !== 1 && scope.row.status !== 2 && scope.row.status !== 4" type="danger" size="mini" style="width:80px" @click="handleDelete(scope.row)">恢复库存</el-button>
          <el-button v-permission="['operation:seckill:suspend']" v-show="scope.row.status === 1 && scope.row.status !== 4" type="danger" size="mini" @click="suspend(scope.row)">暂停</el-button>
          <el-button v-permission="['operation:seckill:start']" v-show="scope.row.status === 2 && scope.row.status !== 4" type="danger" size="mini" @click="start(scope.row)">开启</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-tooltip placement="top" content="返回顶部">
      <back-to-top :visibility-height="100" />
    </el-tooltip>

    <!-- 添加对话框 -->
    <el-dialog :title="dialogTitleMap[dialogStatus]" :visible.sync="dialogFormVisible" :fullscreen="true" :close-on-press-escape="false" center>
      <el-card class="box-card">
        <h3>商品属性(spu)</h3>
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="dataForm"
          status-icon
          label-position="left"
          label-width="150px"
          style="width: 700px; margin-left:50px;"
        >

          <el-form-item label="选择商品" prop="spuId">
            <el-autocomplete
              v-model="dataForm.spuTitle"
              :fetch-suggestions="querySearchGoodsName"
              :trigger-on-focus="false"
              style="width:300px"
              placeholder="请输入商品信息"
              @select="handleSelect"
            >
              <template slot-scope="{ item }">
                <div class="name" style="color:green">{{ item.id }} {{ item.title }}</div>
              </template>
            </el-autocomplete>
            <el-input v-model="dataForm.spuId" type="hidden" />
          </el-form-item>

          <el-form-item label="秒杀时间">
            <el-col :span="11" >
              <el-date-picker
                v-model="dataForm.gmtStart"
                type="datetime"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
                default-time="00:00:00"
                placeholder="选择日期"
                style="width: 100%;" />
            </el-col>
            <el-col :span="2" class="line">&nbsp;&nbsp;&nbsp;&nbsp; 至</el-col>
            <el-col :span="11">
              <el-date-picker
                v-model="dataForm.gmtEnd"
                type="datetime"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
                default-time="23:59:59"
                placeholder="选择日期"
                style="width: 100%;" />
            </el-col>
          </el-form-item>

          <el-form-item label="每人秒杀数量" >
            <el-input-number v-model="dataForm.limitCount" controls-position="right" />
          </el-form-item>

          <el-form-item label="秒杀价格" >
            <el-input-number v-model="dataForm.spuSeckillPrice" :precision="2" controls-position="right" />元
          </el-form-item>

          <el-checkbox v-model="dataForm.orderBuyType">用户自提</el-checkbox>

        </el-form>
      </el-card>

      <el-card class="box-card">
        <h3>商品类型(sku)</h3>
        <!-- <el-button :plain="true" type="primary" @click="handleSkuShow">添加</el-button> -->
        <el-table :data="dataForm.skuList">
          <el-table-column property="id" label="SkuId"/>
          <el-table-column property="barCode" label="Sku条形码" />
          <el-table-column property="title" label="类型名" />
          <el-table-column property="stock" label="库存" />
          <el-table-column property="price" label="现价/元" />
          <el-table-column property="skuSeckillPrice" label="秒杀价格/元" />
          <el-table-column property="stockCount" label="秒杀数量" />
          <el-table-column property="limitCount" label="每人秒杀数量" />

          <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width" >
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="openSkuSeckillPriceUpdateDialog(scope.row)">更新</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 更新秒杀价格的Dialog -->
      <el-dialog :visible.sync="groupShopUpdateSkuPriceDialog" :modal="true" :append-to-body="true" :close-on-click-modal = "false" top="10vh" width="70%" title="更新秒杀价格">
        <el-form
          ref="specForm"
          :model="skuForm"
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="秒杀价格" >
            <el-input-number v-model="skuForm.skuSeckillPrice" :precision="2" controls-position="right" />元
          </el-form-item>
          <el-form-item label="秒杀数量" >
            <el-input-number v-model="skuForm.stockCount" controls-position="right" />
          </el-form-item>
          <el-form-item label="现价">
            {{ skuForm.price }}元
          </el-form-item>
          <el-form-item label="sku类型名">
            {{ skuForm.title }}元
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="groupShopUpdateSkuPriceDialog = false">取消</el-button>
          <el-button type="primary" @click="skuGroupShopUpdate()">确定</el-button>
        </div>
      </el-dialog>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus === 'create'" type="primary" @click="createOrUpdateData">创建</el-button>
        <el-button v-if="dialogStatus === 'update'" type="primary" @click="createOrUpdateData">更新</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<style>
  .table-expand {
    font-size: 0;
  }

  .table-expand label {
    width: 100px;
    color: #99a9bf;
  }

  .table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }

  .gallery {
    width: 80px;
    margin-right: 10px;
  }
</style>

<script>
import { list, create, del, update, suspend, start } from '@/api/seckill'
import BackToTop from '@/components/BackToTop'
import { spuTree } from '@/api/goods'
import { formatDateAndTimeNoSecond } from '@/filters'
import { clearTreeEmptyChildren, dateToStirng } from '@/utils/index'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { detailGoods, searchGoods } from '@/api/goods'

export default {
  name: 'GoodsList',
  components: { BackToTop, Pagination },
  filters: {
    formatGmt(time) {
      if (time == null || time === '') {
        return '无'
      }
      return formatDateAndTimeNoSecond(time)
    }
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      dialogFormVisible: false,
      statusMap: [{ value: 0, name: '未开启' }, { value: 1, name: '秒杀中' }, { value: 2, name: '暂停' }, { value: 3, name: '结束' }, { value: 4, name: '下架' }],
      listQuery: {
        page: 1,
        limit: 20,
        spuName: undefined,
        status: undefined,
        id: undefined
      },
      dialogTitleMap: { create: '创建秒杀商品', update: '修改秒杀商品' },
      dialogStatus: 'create',
      rules: {},
      dataForm: {
        spuId: undefined,
        gmtStart: undefined,
        spuTitle: undefined,
        gmtEnd: undefined,
        groupShopSkus: [],
        skuList: [],
        orderBuyType: false
      },
      goodsOptions: [],
      goodsOption: undefined,
      groupShopUpdateSkuPriceDialog: false,
      skuForm: {},
      spuForm: {},
      state_arr: [{ text: '未开启', type: '' }, { text: '活动中', type: 'success' }, { text: '暂停', type: 'info' }, { text: '结束', type: 'warning' }, { text: '下架', type: 'danger' }]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      list(this.listQuery)
        .then(response => {
          response.data.data.items.forEach(temp => {
            temp.seckillSkuDTOList.forEach(item => {
              item.price = item.price / 100
              item.originalPrice = item.originalPrice / 100
              item.vipPrice = item.vipPrice / 100
              item.skuSeckillPrice = item.skuSeckillPrice / 100
            })
          })
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    refreshDataForm() {
      this.dataForm = {
        spuId: undefined,
        gmtStart: undefined,
        spuTitle: undefined,
        gmtEnd: undefined,
        skuList: [],
        groupShopSkus: []
      }
    },
    openSpuCreateDialog() {
      this.refreshDataForm()
      this.refreshGoodsOptions()
      this.dialogStatus = 'create'
      this.goodsOption = undefined
      this.dialogFormVisible = true
    },
    openSpuUpdateDialog(data) {
      this.refreshDataForm()
      this.refreshGoodsOptions()
      this.dialogStatus = 'update'
      this.goodsOption = 'G_' + data.spuId
      this.dataForm = Object.assign({}, {
        id: data.id,
        spuId: data.spuId,
        automaticRefund: data.automaticRefund,
        spuTitle: data.title,
        gmtStart: new Date(data.gmtStart),
        gmtEnd: new Date(data.gmtEnd),
        minimumNumber: data.minimumNumber,
        skuList: data.seckillSkuDTOList,
        limitCount: data.limitCount,
        spuSeckillPrice: (data.spuSeckillPrice) / 100,
        groupShopSkus: [],
        orderBuyType: data.buyType === 0
      })
      this.dataForm.skuList.forEach(item => {
        item.limitCount = data.limitCount
      })
      this.dialogFormVisible = true
    },
    handleDelete(row) {
      this.$confirm('此操作将永久下架秒杀商品--' + row.title + '--, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(row.id)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '下架成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
            this.handleFilter()
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        return false
      })
    },
    suspend(row) {
      this.$confirm('此操作将暂停商品秒杀--' + row.title + '--, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        suspend(row.id)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '暂停成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
            this.handleFilter()
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        return false
      })
    },
    start(row) {
      this.$confirm('此操作将开启暂停中的商品秒杀--' + row.title + '--, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        start(row.id)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '开启成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
            this.handleFilter()
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        return false
      })
    },
    refreshGoodsOptions() {
      if (this.goodsOptions.length === 0) {
        spuTree().then(response => {
          this.goodsOptions = clearTreeEmptyChildren(response.data.data)
        })
      }
    },
    chooseGoods(e) {
      // 1. 验证是否是商品
      if (e !== undefined) {
        const tag = e[e.length - 1]
        if (this.goodsOption === undefined || this.goodsOption === null || this.goodsOption.length <= 3) {
          this.$notify.error({
            title: '提示',
            message: '请选择商品'
          })
          return false
        }
        // 2. 向后台根据商品ID获取商品信息
        this.dataForm.spuId = tag.substring(2)
        detailGoods(this.dataForm.spuId).then(response => {
          response.data.data.skuList.forEach(item => {
            item.price = item.price / 100
            item.originalPrice = item.originalPrice / 100
            item.vipPrice = item.vipPrice / 100
            item.skuSeckillPrice = item.price
          })
          this.dataForm.skuList = response.data.data.skuList
        }).catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg + ',请重新选择'
          })
        })
      }
    },
    createOrUpdateData() {
      if (this.dataForm.spuId === null || this.dataForm.spuId === undefined || this.dataForm.skuList === null || this.dataForm.skuList === undefined || this.dataForm.skuList.length === 0) {
        this.$notify.error({
          title: '提示',
          message: '请选择商品'
        })
        return false
      }
      if (this.dataForm.gmtStart === null || this.dataForm.gmtStart === undefined || this.dataForm.gmtEnd === null || this.dataForm.gmtEnd === undefined || this.dataForm.gmtStart >= this.dataForm.gmtEnd) {
        this.$notify.error({
          title: '提示',
          message: '请选择活动时间,且开始时间小于结束时间'
        })
        return false
      }
      // 判断秒杀限制 与  秒杀价
      if (this.dataForm.limitCount === null || this.dataForm.limitCount === undefined || this.dataForm.limitCount === '') {
        this.$notify.error({
          title: '提示',
          message: '请填写每人秒杀量'
        })
        return false
      }
      if (this.dataForm.spuSeckillPrice === null || this.dataForm.spuSeckillPrice === undefined || this.dataForm.spuSeckillPrice === '') {
        this.$notify.error({
          title: '提示',
          message: '请填写秒杀价格'
        })
        return false
      }

      // this.dataForm.gmtStart = this.dataForm.gmtStart.getTime()
      // this.dataForm.gmtEnd = this.dataForm.gmtEnd.getTime()
      // 提取skuList中的属性并改名
      for (var i = 0; i < this.dataForm.skuList.length; i++) {
        if (this.dataForm.skuList[i].skuSeckillPrice === null || this.dataForm.skuList[i].skuSeckillPrice === undefined || this.dataForm.skuList[i].skuSeckillPrice === '') {
          this.$notify.error({
            title: '提示',
            message: '请完善商品类型(sku)的信息'
          })
          return false
        }
        if (this.dataForm.skuList[i].stockCount === null || this.dataForm.skuList[i].stockCount === undefined || this.dataForm.skuList[i].stockCount === '') {
          this.$notify.error({
            title: '提示',
            message: '请完善商品类型(sku)的信息'
          })
          return false
        }

        var temp = {}
        temp.skuId = this.dataForm.skuList[i].id
        temp.skuSeckillPrice = this.dataForm.skuList[i].skuSeckillPrice * 100
        temp.stockCount = this.dataForm.skuList[i].stockCount
        temp.barCode = this.dataForm.skuList[i].barCode
        temp.id = this.dataForm.skuList[i].seckillSkuId
        // this.dataForm.skuList[i].colonelDOList=null
        // this.dataForm.skuList[i].skuId=this.dataForm.skuList[i].id;
        this.dataForm.groupShopSkus.push(temp)
      }
      this.dataForm.skuList = JSON.stringify(this.dataForm.groupShopSkus)
      if (this.dataForm.gmtStart instanceof Date) {
        this.dataForm.gmtStart = dateToStirng(this.dataForm.gmtStart)
      }
      if (this.dataForm.gmtEnd instanceof Date) {
        this.dataForm.gmtEnd = dateToStirng(this.dataForm.gmtEnd)
      }
      const requestForm = {
        id: this.dataForm.id,
        gmtStart: new Date(this.dataForm.gmtStart + ':00:00').getTime(),
        gmtEnd: new Date(this.dataForm.gmtEnd + ':00:00').getTime(),

        seckillSkuList: this.dataForm.skuList,
        spuId: this.dataForm.spuId,
        // automaticRefund: this.dataForm.automaticRefund,
        // seckillPrice: this.dataForm.spuSeckillPrice,
        limitCount: this.dataForm.limitCount,
        spuSeckillPrice: parseFloat(this.dataForm.spuSeckillPrice * 100).toFixed(0),
        // seckillPrice: parseFloat(this.dataForm.spuSeckillPrice * 100).toFixed(0),
        orderBuyType: this.dataForm.orderBuyType
      }
      if (this.dialogStatus === 'create') {
        create(requestForm)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '秒杀商品录入成功!'
            })
            this.getList()
          })
          .catch(response => {
            this.$notify.error({
              title: '提示',
              message: response.data.errmsg
            })
          })
      } else if (this.dialogStatus === 'update') {
        update(requestForm)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '秒杀商品更新成功!'
            })
            this.getList()
          })
          .catch(response => {
            this.$notify.error({
              title: '提示',
              message: response.data.errmsg
            })
          })
      }

      this.dialogFormVisible = false
    },
    openSkuSeckillPriceUpdateDialog(data) {
      this.skuForm = undefined
      this.groupShopUpdateSkuPriceDialog = true
      this.skuForm = data
    },
    skuGroupShopUpdate(data) {
      this.groupShopUpdateSkuPriceDialog = false
    },
    querySearchGoodsName: function(queryString, cb) {
      searchGoods(queryString)
        .then(res => {
          this.userInfo = res.data.data
          for (const i of this.userInfo) {
            i.value = i.title
          }
          cb(this.userInfo)
        })
        .catch(() => {
          this.$notify.error({
            title: '失败',
            message: '没有此用户'
          })
        })
    },
    handleSelect: function(item) {
      this.dataForm.spuId = item.id
      detailGoods(this.dataForm.spuId).then(response => {
        response.data.data.skuList.forEach(item => {
          item.price = item.price / 100
          item.originalPrice = item.originalPrice / 100
          item.vipPrice = item.vipPrice / 100
          item.skuGroupShopPrice = item.price
        })
        this.dataForm.skuList = response.data.data.skuList
        console.log(this.dataForm.skuList)
      })
    }
  }

}
</script>
